<template>
  <div class="vb-areas-form">
    <div v-if="!readonly" style="text-align: right;padding-bottom:10px">
      <el-button type="primary" @click="addTableRow()">添加</el-button>
    </div>
    <el-table
      border
      :data="data"
    >
      <el-table-column
        type="index"
        width="55"
        align="center"
        label="序号"
      />
      <el-table-column align="center" label="省市区">
        <template slot-scope="{row,$index}">
          <RegionSelect v-if="!readonly" v-model="row.areas" @change="v=>{changeAreas(v,$index)}" />
          <span v-else>
            {{ row.province }} {{ row.city }}  {{ row.county }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="地址">
        <template slot-scope="{row}">
          <el-input v-if="!readonly" v-model="row.address" style="width:100%" />
          <span v-else>{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="!readonly"
        label="操作"
        fixed="right"
        width="100"
        class-name="table-opt-col"
      >
        <template slot-scope="{$index}">
          <el-button type="text" @click="delTableRow($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import RegionSelect from '@/components/RegionSelect'
export default {
  name: 'VbAreasForm',
  components: { RegionSelect },
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: []

    }
  },
  computed: {
    data: {
      get() {
        this.value.forEach(m => {
          if (m.province && m.city && m.county) {
            m.areas = [m.province, m.city, m.county]
          } else {
            m.areas = []
          }
        })
        return this.value
      },
      set(val) {
        console.log('set:', val)
        val.forEach(m => {
          if (m.areas && m.areas.length > 0) {
            m.province = m.areas[0]
            m.city = m.areas[1]
            m.county = m.areas[2]
          }
        })
        this.$emit('input', val)
      }

    }
  },
  mounted() {
    // this.list = JSON.parse(JSON.stringify(this.data))
  },
  methods: {
    changeAreas(v, i) {
      console.log('data:', this.data)
      this.data[i].areas = v
      this.data = JSON.parse(JSON.stringify(this.data))
    },
    delTableRow(i) {
      const list = JSON.parse(JSON.stringify(this.data))
      list.splice(i, 1)
      this.$emit('input', list)
    },
    addTableRow() {
      console.log('addTableRow-data:', this.data)

      const list = JSON.parse(JSON.stringify(this.data))
      console.log('addTableRow-list:', list)
      list.push({
        address: '',
        city: '',
        county: '',
        province: '',
        areas: []
      })
      this.$emit('input', list)
    }
  }
}
</script>
